package com.vf.admin.utils.aliyunoss;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.http.HttpResponse;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.AppDynamicService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.AppDynamic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.*;

import static com.vf.admin.common.Constants.zengjia;

/**
 * <p>Title : 阿里云鉴黄</p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows10</p>
 *
 * @Author : NemoMeng
 * @Date 2023/6/29 17:02
 */
@Controller
@RequestMapping("/aliYunCheck")
public class CheckUtilsController extends ClientBaseController {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    AppDynamicService appDynamicService;

    @ResponseBody
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    public void image() {
        //取出GREENIMAGE 开头的 key
        Set<String> keys = redisUtil.keys(RedisKeys.GREEN_IMAGES + "*");
        if (ObjectUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //取出url
                String urls = (String) redisUtil.get(key);
                //截取id 从第11位开始截取
                Integer id = Integer.valueOf(key.substring(11));
                System.out.println(id);
                //获取url
                String[] asList = urls.split(",");
                //鉴黄
                List<Boolean> flag = new ArrayList<>();
                for (String urlCheck : asList) {
                    boolean b = OssCheckUtils.imageSyncCheckV2(urlCheck);
                    flag.add(b);
                }
                //执行数据库更新操作
                if (ObjectUtil.isNotEmpty(flag)) {
                    boolean contains = flag.contains(false);
                    if (!contains) {
                        //查询
                        AppDynamic appDy = appDynamicService.getByid(id);
                        if (ObjectUtil.isNotEmpty(appDy)) {
                            if (appDy.getStatus().equals(2)) {
                                //修改动态状态
                                appDynamicService.updateStatus(id, 1);
                                //增加动态数量
                                appUserService.dongtaiallUpdate(appDy.getUserid(), zengjia);
                                //增加新增动态数量
                                appUserService.dongtaiNewUpdate(appDy.getUserid());
                                //增加任务
                                appDailyTasController.getAwardEveryDay(appDy.getUserid(), ClientConstants.TaskEveryDay.SEND_DYNAMIC);
                                //删除redis
                                String keyId = String.format(RedisKeys.GREEN_IMAGE, id);
                                redisUtil.del(keyId);
                            }
                        }
                    } else {
                        //删除redis
                        String keyId = String.format(RedisKeys.GREEN_IMAGE, id);
                        redisUtil.del(keyId);
                    }
                }
            }
        }
    }

    /**
     * 视频鉴黄
     */
    @ResponseBody
    @RequestMapping(value = "/video", method = RequestMethod.POST)
    public void video() {
        //首先获取redis数据
        //GREENVEIDO 开头的 key
        Set<String> keys = redisUtil.keys(RedisKeys.GREEN_VIEDOS + "*");
        if (ObjectUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //取出url taskId
                String taskId = (String) redisUtil.get(key);
                //截取id 从第11位开始截取
                Integer id = Integer.valueOf(key.substring(11));
                //查询鉴黄结果
                System.out.println(taskId);
                //发送到阿里云鉴黄
                HttpResponse httpResponse = OssCheckUtils.videoCall(taskId);
                //鉴黄
                List<Boolean> flag = new ArrayList<>();
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = null;
                    try {
                        scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
//                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // 每一个视频的检测结果。
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // 单个视频的处理结果。
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (280 == taskCode) {
                                // 检测中。
                                // taskId。
//                                System.out.println("taskId:" + ((JSONObject) taskResult).getString("taskId"));

                            } else if (200 == taskCode) {
                                // taskId。
//                                System.out.println("taskId:" + ((JSONObject) taskResult).getString("taskId"));
                                // 检测结果。
                                JSONArray results = ((JSONObject) taskResult).getJSONArray("results");
                                for (Object result : results) {
                                    // 视频检测结果的分类。
//                                    System.out.println("label:" + ((JSONObject) result).getString("label"));
                                    // 置信度分数，取值范围：0（表示置信度最低）~100（表示置信度最高）。
//                                    System.out.println("rate:" + ((JSONObject) result).getString("rate"));
                                    // 视频检测场景，与调用请求中的检测场景一致。
//                                    System.out.println("scene:" + ((JSONObject) result).getString("scene"));
                                    // 建议您执行的后续操作。取值：
                                    // pass：结果正常，无需进行其他操作。
                                    // review：结果不确定，需要人工审核。
                                    // block：结果违规，建议直接删除或者限制公开。
//                                    System.out.println("suggestion:" + ((JSONObject) result).getString("suggestion"));
                                    if (((JSONObject) result).getString("suggestion").equals("pass")) {
                                        flag.add(true);
                                    }
                                }
                            } else {
                                // 单个视频处理失败，原因视具体的情况详细分析。
//                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * 表明请求整体处理失败，原因视具体的情况详细分析。
                         */
//                        System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                    //执行数据库操作
                    if (ObjectUtil.isNotEmpty(flag)) {
                        boolean contains = flag.contains(false);
                        if (!contains) {
                            AppDynamic appDy = appDynamicService.getByid(id);
                            if (appDy.getStatus().equals(2)) {
                                //修改动态状态
                                appDynamicService.updateStatus(id, 1);
                                //增加动态数量
                                appUserService.dongtaiallUpdate(appDy.getUserid(), zengjia);
                                //增加新增动态数量
                                appUserService.dongtaiNewUpdate(appDy.getUserid());
                                //增加任务
                                appDailyTasController.getAwardEveryDay(appDy.getUserid(), ClientConstants.TaskEveryDay.SEND_DYNAMIC);
                                //删除redis
                                String keyId = String.format(RedisKeys.GREEN_VIEDO, id);
                                redisUtil.del(keyId);
                            }
                        } else {
                            //删除redis
                            String keyId = String.format(RedisKeys.GREEN_VIEDO, id);
                            redisUtil.del(keyId);
                        }
                    }
                } else {
//                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            }

        }
    }


}
